package com.xxl.javaWork_15;

import java.util.Random;

/**
 * @Author: xiaxinlin
 * @Date: 2020/12/14 18:10
 */
public class SaleRailTicket implements Runnable {

    private int ticket_G7665=1000;
    private int ticket_G7585=1000;
    private boolean flag=true;


    public static void main(String[] args) {
        SaleRailTicket railTicket = new SaleRailTicket();
        Thread thread1 = new Thread(railTicket);
        Thread thread2 = new Thread(railTicket);
        Thread thread3 = new Thread(railTicket);
        Thread thread4 = new Thread(railTicket);
        Thread thread5 = new Thread(railTicket);
        thread1.setName("窗口1");
        thread2.setName("窗口2");
        thread3.setName("窗口3");
        thread4.setName("窗口4");
        thread5.setName("窗口5");
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
        thread5.start();
    }

    @Override
    public void run() {
        while (true){
            saleTicket();
            if (!flag){
                break;
            }
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void saleTicket(){
        if (ticket_G7585==0&&ticket_G7665==0){
            flag=false;
            return;
        }
        Random random = new Random();
        int ticketId = random.nextInt(2);
        if (ticketId==1&&ticket_G7585>0){
            System.out.println(Thread.currentThread().getName()+"买到了G7587列次的第"+(1000-ticket_G7585+1)+"张票");
            ticket_G7585--;
        }else if (ticket_G7665>0){
            System.out.println(Thread.currentThread().getName()+"买到了G7665列次的第"+(1000-ticket_G7665+1)+"张票");
            ticket_G7665--;
        }
    }
}
